package com.crm.controller.settings;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.crm.Business.CompareSrcVO;
import com.crm.beans.PurchaseOrderVO;
import com.crm.beans.QuotParts;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PODAO;
import com.crm.dao.PartSourcesDAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.QuotPartsDAO;
import com.crm.dao.QuotationDAO;
import com.crm.dao.SourceCompareDAO;
import com.crm.dao.SourceInfoDAO;
import com.crm.dao.SourcesDAO;
import com.crm.dao.SupplierDAO;
import com.crm.dao.SupplyOrderDAO;
import com.crm.entity.Business;
import com.crm.entity.Opportunity;
import com.crm.entity.PO;
import com.crm.entity.Parts;
import com.crm.entity.Quotation;
import com.crm.entity.SourceInfo;
import com.crm.entity.Sourcecompare;
import com.crm.entity.Sources;
import com.crm.entity.Supplier;
import com.crm.entity.SupplyOrder;

@Controller
@RequestMapping("/history")
public class HistoryController {
	@RequestMapping("/enquiry.do")
	public ModelAndView enquiry(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Enquiry Controller Startted");
		model=new ModelAndView("/jsp/history/Enquiry.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO odao=new OpportunityDAO();
		PartsDAO pdao=new PartsDAO();
		Opportunity opp=null;
		try {
			opp = OpportunityDAO.getSingleInstance().getByRef(ref, busid);	
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		List<Parts> p = null;
		try {
			p = pdao.getParts(ref, busid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addObject("opportunity",opp);
		model.addObject("parts",p);
		System.out.println("Enquiry Controller Ending");
		return model;
	}
	@RequestMapping("/expoSource.do")
	public ModelAndView expoSource(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Export Controller Startted");
		model=new ModelAndView("/jsp/history/ExportToSource.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO odao=new OpportunityDAO();
		PartSourcesDAO psdao=new PartSourcesDAO();
		PartsDAO pdao=new PartsDAO();
		Opportunity opp=null;
		try {
			opp = OpportunityDAO.getSingleInstance().getByRef(ref, busid);	
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		List<Parts> parts = null;
		try {
			parts = pdao.getParts(ref, busid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Sources> ps = null;
		try {
			ps = psdao.getCompPartSources(opp.getId(), busid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addObject("parts",parts);
		model.addObject("sources",ps);
		System.out.println("Export Controller Ending");
		return model;
	}
	@RequestMapping("/importSource.do")
	public ModelAndView importSource(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Import Controller Startted");
		model=new ModelAndView("/jsp/history/ImportSource.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO odao=new OpportunityDAO();
		Opportunity opp=null;
		CompareSrcVO cmpSrcVo=new CompareSrcVO();
		try {
			opp = OpportunityDAO.getSingleInstance().getByRef(ref, busid);	
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		SourceInfoDAO sidao=new SourceInfoDAO();
		
		List<SourceInfo> lsi = new ArrayList<SourceInfo>();
		try {
			lsi = sidao.getAllPaartsNSuppliers(opp.getId(), busid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SourcesDAO sodao=new SourcesDAO();
		PartsDAO pdao=new PartsDAO();
		Parts p=new Parts();
		Supplier sup=new Supplier();
		SupplierDAO supdao=new SupplierDAO();
		List<CompareSrcVO> lcmpvo=new ArrayList<CompareSrcVO>(); 
		for(SourceInfo si:lsi){
			try {
				p=new Parts();
				sup=new Supplier();
				cmpSrcVo=new CompareSrcVO();
				Sources so=sodao.findById(si.getSourceid(), busid);
				p=pdao.findById(si.getPrtnum(), busid, opp.getId());
				sup=supdao.findById(si.getSuplierid(), busid);
				cmpSrcVo.setSourceCurrency(si.getCurrency());
				cmpSrcVo.setSourceName(so.getSourceName());
				cmpSrcVo.setSupplierName(sup.getName());
				cmpSrcVo.setPartNum(p.getPrtnum());
				cmpSrcVo.setAvailbleQty(si.getQty_available());
				cmpSrcVo.setUprice(si.getUtprice());
				cmpSrcVo.setRequiredQty(si.getReq_qty());
				cmpSrcVo.setMoq(si.getMoq());
				cmpSrcVo.setConditions(si.getConditions());
				cmpSrcVo.setMake(si.getMake());
				cmpSrcVo.setOffPartNo(si.getOfferPartNo());
				cmpSrcVo.setStdpackqty(si.getStdpackqty());
				cmpSrcVo.setDesc(p.getDescription());
				lcmpvo.add(cmpSrcVo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		model.addObject("sourceInfo",lcmpvo);
		System.out.println("Import Controller Ending");
		return model;
	}
	@RequestMapping("/compareSource.do")
	public ModelAndView compareSource(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Compare Controller Startted");
		model=new ModelAndView("/jsp/history/CompareSource.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO oprD=new OpportunityDAO();
			List<CompareSrcVO> listscompare=new ArrayList<CompareSrcVO>();
			Opportunity o = null;
			try {
				o = OpportunityDAO.getSingleInstance().getByRefNo(busid,ref);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			int rfnum=o.getId();
			SourceInfoDAO siDAO=new SourceInfoDAO();
			List<SourceInfo> srcInfo = null;
			try {
				srcInfo = siDAO.getSrcDetails(rfnum,busid);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("the sourceInfo list is  "+srcInfo);
			if(srcInfo!=null){
			Iterator<SourceInfo> itr=srcInfo.iterator();
			int k=0;
			while(itr.hasNext()){
				Object ob=itr.next();
				SourceInfo si=(SourceInfo)ob;
				int pr=si.getPrtnum();
				System.out.println("The partno is "+pr);
				int req_qty=si.getReq_qty();
				int srid=si.getSourceid();
				int splid=si.getSuplierid();
				float uprice=si.getUtprice();
				String soCurrency=si.getCurrency();
				String ofrPart=si.getOfferPartNo();
				int availQty=si.getQty_available();
				int moq=si.getMoq();
				
				int spq=si.getStdpackqty();
				String cond=si.getConditions();
				PartsDAO pDAO=new PartsDAO();
				Parts prt = null;
				try {
					prt = pDAO.findById(pr,busid,rfnum);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
				String prtNum=prt.getPrtnum();

				String desc=prt.getDescription();
				SourcesDAO sDAO=new SourcesDAO();
				
				Sources sd = new Sources();
				try {
					sd = sDAO.findById(srid,busid);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				String srcName=null;
				try{
					srcName=sd.getSourceName();
				}catch(Exception e){
					System.out.println("Source Name Is :"+srcName);
					e.printStackTrace();
				}
					
				String splName="";
				SupplierDAO supDAO=new SupplierDAO();
				if(splid!=0){
					
				Supplier spl = null;
				try {
					spl = supDAO.findById(splid,busid);
				} catch (Exception e) {
					e.printStackTrace();
				}	
				splName=spl.getName();
				}
					k++;
					CompareSrcVO csrc=new CompareSrcVO(false,k,prtNum,desc,ofrPart,req_qty,srcName,splName,uprice,soCurrency,availQty,moq,cond,spq,si.getPrtnum());
					listscompare.add(csrc);
				
			
			}
			}
		model.addObject("lscompare",listscompare);
		System.out.println("Compare Controller Ending");
		return model;
	}
	@RequestMapping("/quotation.do")
	public ModelAndView quotation(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Quotation Controller Startted");
		model=new ModelAndView("/jsp/history/Quotation.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO oprD=new OpportunityDAO();
		Opportunity o = new Opportunity();;
		QuotPartsDAO qpdao=new QuotPartsDAO();
		Quotation q=new Quotation();
		List<com.crm.entity.QuotParts> lqp=new ArrayList<com.crm.entity.QuotParts>();
		List<QuotParts> lcqp=new ArrayList<QuotParts>();
		QuotParts qp=new QuotParts();
		SourceCompareDAO scdao=new SourceCompareDAO();
		SourcesDAO sodao=new SourcesDAO();
		SupplierDAO supdao=new SupplierDAO();
		try {
			o = OpportunityDAO.getSingleInstance().getByRefNo(busid,ref);
			QuotationDAO qdao=new QuotationDAO();
			q=qdao.getPendingQuot(o.getId(), busid);
			System.out.println("Quotation Id Is: "+q.getId());
			lqp=qpdao.getPartsByQuotId(q.getId(), o.getId(), busid);
			Sourcecompare sc=new Sourcecompare();
			for(int i=0;i<lqp.size();i++){
				sc=scdao.findByPartIdBusid(o.getId(), lqp.get(i).getPartid().getPartid(), busid);
				String source=null;
				try{
					sodao.findById(sc.getSrcnum(),busid).getSourceName();
				}catch(Exception e){
					e.printStackTrace();
				}
				qp=new QuotParts(lqp.get(i).getPartid().getPrtnum()+"",lqp.get(i).getMake()+"",lqp.get(i).getPartid().getDescription()+"",lqp.get(i).getQty()+"",source,supdao.findById(sc.getSupplier(),busid).getName(),sc.getUnitprice()+"",lqp.get(i).getFright()+"",lqp.get(i).getAssmbValue()+"",lqp.get(i).getBcd()+"",lqp.get(i).getTotal()+"",lqp.get(i).getMargin()+"",lqp.get(i).getUtprice()+"",lqp.get(i).getQuotPrice()+"",lqp.get(i).getDelivery()+"");
				lcqp.add(qp);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addObject("quotation",q);
		model.addObject("quotparts",lcqp);
		System.out.println("Quotation Controller Ending");
		return model;
	}
	@RequestMapping("/supplyOrder.do")
	public ModelAndView supplyOrder(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Supply Order Controller Startted");
		model=new ModelAndView("/jsp/history/SupplyOrder.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO oprD=new OpportunityDAO();
		Opportunity o = new Opportunity();;
		SupplyOrderDAO sodao=new SupplyOrderDAO();
		QuotationDAO qdao=new QuotationDAO();
		PartsDAO pdao=new PartsDAO();
		List<QuotParts> qplist=new ArrayList<QuotParts>();
		List<SupplyOrder> liso =new ArrayList<SupplyOrder>();
		String bgdate=null;
		String bgedate=null;
		String wargdate=null;
		String waredate=null;
		String pino=null;
		String soNo=null;
		String piDate=null;
		String soStDate=null;
		String soEndDate=null;
		try {
			o=OpportunityDAO.getSingleInstance().getByRefNo(busid, ref);
			Quotation q=qdao.getPendingQuot(o.getId(), busid);
			liso = sodao.getByQuotid(busid, q.getId());
			for(int i=0;i<liso.size();i++){
				Parts p=pdao.findById(liso.get(i).getPrtid(), busid, o.getId());
				QuotParts qp=new QuotParts();
				qp.setPartNo(p.getPrtnum());
				qp.setDesc(p.getDescription());
				qp.setQty(liso.get(i).getQty()+"");
				qp.setUnitPrice(liso.get(i).getPrice()+"");
				qp.setDesc(liso.get(i).getDiscount()+"");
				qp.setUnitValue((liso.get(i).getPrc_aftr_discount()/liso.get(i).getQty())+"");
				qp.setTotalcost(liso.get(i).getPrc_aftr_discount()+"");
				qplist.add(qp);
				if(liso.get(i).getBgdate()!=null && liso.get(i).getBgedate()!=null){
					bgdate=liso.get(i).getBgdate().toString();
					bgedate=liso.get(i).getBgedate().toString();
				}
				if(liso.get(i).getWargdate()!=null && liso.get(i).getWaredate()!=null){
					wargdate=liso.get(i).getWargdate().toString();
					waredate=liso.get(i).getWaredate().toString();
				}
				pino=liso.get(i).getInvoice();
				soNo=liso.get(i).getSuplyOrderNum();
				if(liso.get(i).getPi_date()!=null){
					piDate=liso.get(i).getPi_date().toString();
				}
				if(liso.get(i).getSoStartDate()!=null){
					soStDate=liso.get(i).getSoStartDate().toString();
				}
				if(liso.get(i).getSoEndDate()!=null){
					soEndDate=liso.get(i).getSoEndDate().toString();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addObject("quotpartslist",qplist);
		model.addObject("bgdate",bgdate);
		model.addObject("bgedate",bgedate);
		model.addObject("wargdate",wargdate);
		model.addObject("waredate",waredate);
		model.addObject("piNo",pino);
		model.addObject("soNo",soNo);
		model.addObject("piDate",piDate);
		model.addObject("soStartDate",soStDate);
		model.addObject("soEndDate",soEndDate);
		System.out.println("Supply Order Controller Ending");
		return model;
	}
	@RequestMapping("/purchaseOrder.do")
	public ModelAndView purchaseOrder(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response){
		System.out.println("Supply Order Controller Startted");
		model=new ModelAndView("/jsp/history/PurchaseOrder.jsp");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		String ref=request.getParameter("refno");
		int busid=bus.getBusinessId();
		//OpportunityDAO oprD=new OpportunityDAO();
		PODAO podao=new PODAO();
		PartsDAO pdao=new PartsDAO();
		Opportunity o = new Opportunity();
		SourcesDAO sodao=new SourcesDAO();
		SupplierDAO supdao=new SupplierDAO();
		List<PurchaseOrderVO> lipovo=new ArrayList<PurchaseOrderVO>();
		try {
			o=OpportunityDAO.getSingleInstance().getByRefNo(busid, ref);
			int enqid=o.getId();
			List<PO> lpo=podao.getPOByEnqidBusid(enqid, busid);
			for(int i=0;i<lpo.size();i++){
				String partnum=pdao.findById(lpo.get(i).getPartId(), busid, enqid).getPrtnum();
				int qty=lpo.get(i).getQty();
				String source=null;
				try{
					source=sodao.findById(lpo.get(i).getSourceId(),busid).getSourceName();
				}catch(Exception e){
					e.printStackTrace();
				}
					
				String supplier=supdao.findById(lpo.get(i).getSupplierId(),busid).getName();
				float unitPrice=lpo.get(i).getUnitPrice();
				float sum=lpo.get(i).getSum();
				int moq=lpo.get(i).getMoq();
				String total=lpo.get(i).getTotalPrice()+"";
				String poNo=lpo.get(i).getPoNumber();
				String supRefNo=lpo.get(i).getSupplierRefNo();
				PurchaseOrderVO povo=new PurchaseOrderVO(partnum,qty,source,supplier,unitPrice,sum,moq,poNo,supRefNo,total);
				lipovo.add(povo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addObject("povo",lipovo);
		System.out.println("Supply Order Controller Ending");
		return model;
	}
	

}
